package realtime.util;

import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {
    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean isUnderscoreToCamel) throws Exception {
        //创建集合用于存放结果数据
        ArrayList<T> list = new ArrayList<>();

        //预编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //执行查询
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        //遍历结果集,将每行数据封装为T对象
        //行
        while (resultSet.next()) {
            //创建T对象
            T t = clz.newInstance();

            //列
            for (int i = 0; i < columnCount; i++) {
                //获取列名和列值
                //列名
                String columnName = metaData.getColumnName(i + 1);
                //列值
                Object columnValue = resultSet.getObject(columnName);

                //是否将表中字段转换为小驼峰
                if (isUnderscoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }
                //将属性以及值设置进T对象
                BeanUtils.setProperty(t, columnName, columnValue);
        }
            //将T对象放入集合
            list.add(t);
        }


        return list;
    }

}
